package mi.payment.utils.transaction;

import android.text.TextUtils;

import mi.payment.bean.db.TradeData;
import mi.payment.constants.Configs;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.MerManagerSettings;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.QPSParamsOperation;
import mi.payment.settings.QPSParamsSetting;
import mi.payment.settings.SignOperation;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.settings.TerminalKeyDataOperations;
import mi.payment.settings.TerminalKeyManagementBean;
import mi.payment.utils.MustParameterCalibration;
import mi.payment.utils.SystemDateTime;
import mi.payment.utils.secure.TerminalSecure;
import sunmi.sunmiui.utils.LogUtil;

/**
 * @author Created by KenMa on 2017/8/1.
 */

public class CustomParamsInitTask extends ParamsInitTask {

    @Override
    protected String doTransactionSelf() {
        String ret = "E4";
        MerchantSettingsOperation mso = MerchantSettingsOperation.getInstance();
        MerManagerSettings managerParams = mso.getMerManagerSettings();
        boolean isDownloadParamsOnce = SystemParamsOperation.getInstance().isDownloadParamsOnce();
        // 如果商户号或者终端号为空就判断没有下载过终端参数
        // 签到前是否初始化机具
        boolean noDownloadParams = TextUtils.isEmpty(managerParams.getMerchantNum())
                || TextUtils.isEmpty(managerParams.getTerminalNum());

        if (noDownloadParams || !isDownloadParamsOnce) {
            // 签到前是否初始化机具
            LogUtil.e(TAG, "Init Machine!");
            String kek = Configs.getInstance().KEK();
            int saveResult = TerminalSecure.saveKEK(kek);
            if (!(saveResult == 0 || saveResult == 4)) {
                return ret;
            }
            InitMachineTask initMachineTask = new InitMachineTask(context);
//            ret = initMachineTask.syncExecute();
//            if (!TextUtils.equals("00", ret)) {
//                return ret;
//            }
        }
        if (!noDownloadParams) {
            LogUtil.e(TAG, "Machine info already exist");
        }

        // 签到前是否下载主密钥
        TerminalKeyManagementBean tkmBean = TerminalKeyDataOperations.getInstance().getTerminalKeyManagementBean();
        boolean noDownloadTMK = tkmBean == null || !tkmBean.isHasDownloadTMK();

        if (noDownloadTMK || !isDownloadParamsOnce) {
            // 签到前是否下载主密钥
            LogUtil.e(TAG, "TMK Download！");
            TMKDownloadTask task = new TMKDownloadTask(context);
            ret = task.syncExecute();
            if (!TextUtils.equals("00", ret)) {
                return ret;
            }
        }
        if (!noDownloadTMK) {
            LogUtil.e(TAG, "TMK Already exist");
        }

        // 签到前是否下载终端参数
        MerchantParamsDownloadTask merchantParamsDownloadTask = new MerchantParamsDownloadTask(context);
        ret = merchantParamsDownloadTask.syncExecute();
        if (!TextUtils.equals("00", ret)) {
            return ret;
        }

        // 参数校验
        if (!MustParameterCalibration.canToNext()) {
            ret = "E5";
            return ret;
        }

        TradeData tradeData = params[0];
        PayDetail payDetail = tradeData.getPayDetail();
        managerParams = mso.getMerManagerSettings();
        payDetail.setTerminalNo(managerParams.getTerminalNum());
        payDetail.setMerchantNo(managerParams.getMerchantNum());
        // 签到
        SignTask signTask = new SignTask(context);
        ret = signTask.syncExecute(params);
        if (!TextUtils.equals("00", ret)) {
            return ret;
        }

        // 签到后是否下载双免参数
        if (Configs.getInstance().PARAM_INIT_QPS_BIN_DOWNLOAD()) {
            QpsDownloadTask task = new QpsDownloadTask(context);
            ret = task.syncExecute();
            if (!TextUtils.equals("00", ret)) {
                return ret;
            }

            QPSParamsSetting setting = QPSParamsOperation.getInstance().getQPSParamsSettings();
            String cardBinB = setting.getCardBinB();
            if (TextUtils.isEmpty(cardBinB)) {
                CardBinDownloadTask taskB = new CardBinDownloadTask(context);
                taskB.initBinBParams();
                // 下载卡BIN B
                ret = taskB.syncExecute();
                if (!TextUtils.equals("00", ret)) {
                    return ret;
                }
                CardBinDownloadTask taskC = new CardBinDownloadTask(context);
                taskC.initBinCParams();
                // 下载卡BIN C(黑名单)
                ret = taskC.syncExecute();
                if (!TextUtils.equals("00", ret)) {
                    return ret;
                }
            }
        }

        LogUtil.e(TAG, "Sign Success!");

        downloadCapkAndAid();

        if (TextUtils.equals("00", ret)) {
            // 保存签到时间
            int time = SystemDateTime.getCurrentYYYYMMDD();
            SignOperation.getInstance().saveLastSignTime(time);
            ParamsInitTask.isChecked = true;
        }
        return ret;
    }

}
